package com.szmmsoft.mp.common.model;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页数据返回
 *
 * @author ethan
 * @version 1.0.0
 * @since 2024-10-12
 */
@Data
public class PageVO<T> {
    @ApiModelProperty(name = "总条数", example = "10")
    private Long total = 0L;
    @ApiModelProperty(name = "当前页数", example = "1")
    private Long page = 0L;
    @ApiModelProperty(name = "列表数据")
    private List<T> list;

    /**
     * 构建分页数据
     *
     * @param page
     * @param <L>
     * @return
     */
    public static <L> PageVO<L> build(IPage<L> page) {
        if (page == null) {
            return empty();
        }
        return build(page.getCurrent(), page.getTotal(),
                page.getRecords());
    }

    /**
     * 构建数据分页
     *
     * @param page
     * @param targetClass
     * @param <L>
     * @param <V>
     * @return
     */
    public static <L, V> PageVO<V> build(IPage<L> page, Class<V> targetClass) {
        if (page == null) {
            return empty();
        }
        return build(page.getCurrent(), page.getTotal(),
                BeanUtil.copyToList(page.getRecords(),
                        targetClass));
    }

    /**
     * 根据数据构建分页
     *
     * @param page
     * @param total
     * @param list
     * @return
     * @param <V>
     */
    private static <V> PageVO<V> build(Long page, Long total, List<V> list) {
        PageVO<V> pageVO = new PageVO<>();
        pageVO.setList(list);
        pageVO.setPage(page);
        pageVO.setTotal(total);
        return pageVO;
    }

    /**
     * 空分页信息
     *
     * @param <L> 列表数据类型
     * @return 分页信息
     */
    private static <L> PageVO<L> empty() {
        PageVO<L> pageResp = new PageVO<>();
        pageResp.setList(new ArrayList<>(0));
        return pageResp;
    }

}
